package com.task.core.test;

import java.util.List;
import java.util.Random;

public class WeightedRandomSelector<T> {
    private final List<Entry<T>> entries;
    private final Random rand;
    private int totalWeight;

    public WeightedRandomSelector(List<Entry<T>> entries) {
        this.entries = entries;
        this.rand = new Random();
        this.totalWeight = 0;
        for (Entry<T> entry : entries) {
            this.totalWeight += entry.weight;
        }
    }

    public T select() {
        if (totalWeight == 0) {
            return null;
        }
        int randNum = rand.nextInt(totalWeight) + 1;
        int accumulatedWeight = 0;
        for (Entry<T> entry : entries) {
            accumulatedWeight += entry.weight;
            if (accumulatedWeight >= randNum) {
                return entry.item;
            }
        }
        return null;
    }

    public static class Entry<T> {
        public T item;
        public int weight;

        public Entry(T item, int weight) {
            this.item = item;
            this.weight = weight;
        }
    }
}

